package com.mmg.cosplay.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.mmg.cosplay.entity.R;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalException {

    //处理全局异常
    @ExceptionHandler(value = Exception.class) //用来处理指定的异常 value属性：用来指定异常类型
    public ResponseEntity<?> exception(Exception ex) {
        return R.error(ex.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleValidException(MethodArgumentNotValidException e) {
        return R.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public ResponseEntity<?> handlerNotLoginException(NotLoginException nle)
            throws Exception {

        // 打印堆栈，以供调试
        nle.printStackTrace();

        // 判断场景值，定制化异常信息
        String message = "";
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未提供token";
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "token无效";
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "token已过期";
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "token已被顶下线";
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "token已被踢下线";
        } else {
            message = "当前会话未登录";
        }

        // 返回给前端
        return R.error(message);
    }

    @ExceptionHandler(NotPermissionException.class)
    public ResponseEntity<?> handleNotPermissionException(NotPermissionException e) {
        return R.error("权限不足", null);
    }
}
